<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Emailer {
	private $CI;
	
	public function __construct()
	{
		$this->CI =& get_instance();
	}
	
	// handle methods prefixed with deliver_*
	// the only argument passed should be an array, formatted like such:
	// array(
	//	'to' => 'someone@example.com',
	//	'subject' => 'hello!',
	//	'data' => array('data' => array(tpl vars to be parsed), 'from' => 'optional from email addy')
	// )
	public function __call($m, $a)
	{
		if (preg_match('/^deliver_(.*)/', $m, $matches))
		{
			$tpl_name = $matches[1];
			$args	  = $a[0];
			$this->_send_email($tpl_name, $args['to'], $args['subject'], $args['data']);
		}
	}
	
	private function _send_email($tpl, $to, $subject, $params = array())
	{
		// set defaults
		$from = isset($params['from']) ? $params['from'] : 'no-reply@bricabox.com';
		$data = isset($params['data']) ? $params['data'] : array();
		
		// load and parse the template
		if (!file_exists(APPPATH."views/email/{$tpl}.php"))
		{
			show_error("missing email template at email/{$tpl}.php");
			die();
		}
		else
			$parsed = $this->CI->parser->parse("email/{$tpl}.php", $data, true); // return a string
		
		// deliver!
		$_parsed = preg_replace("/\r|\n|\r\n/", '/', $parsed);
		log_message('debug', "mailer: sending message [$to $subject] with body: $_parsed");
		
		// use CI's email lib here
		$this->CI->load->library('email');
		$this->CI->email->from($from, $from);
		$this->CI->email->to($to);
		$this->CI->email->subject($subject);
		$this->CI->email->message($parsed);
		$r = $this->CI->email->send();
		$this->CI->email->clear();
		
		log_message('debug', "mailer: result -> " . var_dump((string)$r));
		
		if ($r === false)
		{
			log_message('debug', 'mailer: failed');
			log_message('debug', 'mailer: fail msg: ' . $this->CI->email->print_debugger());
			//die($this->CI->email->print_debugger());
		}
		
		
	}
}
?>